package com.bawei.newsapplication.base

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType

/**
 * 作者: 谢庆平
 * 时间: 2024/10/15 17:18
 * 描述:
 */
abstract class BaseFragment<VM: ViewModel,DB: ViewDataBinding>(private var layoutId:Int) : Fragment() {
    lateinit var mViewModel: VM

    lateinit var mDataBinding:DB
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mDataBinding= DataBindingUtil.inflate(inflater,layoutId,container,false)
        mDataBinding.lifecycleOwner=this
        return mDataBinding.root
    }
//onActivityCreated
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

    var type=javaClass.genericSuperclass as ParameterizedType
    var classVM=type.actualTypeArguments[0] as Class<VM>
    mViewModel= ViewModelProvider(this)[classVM]

    initView()
    dataObserve()

    }

    abstract fun initView()

    abstract fun dataObserve()

    override fun onDestroy() {
        super.onDestroy()

        if(mDataBinding!=null){
            mDataBinding.unbind()
        }
    }
}